import { ElMessageBox } from 'element-plus'
import { PointerEvent } from 'leafer-ui'
import { BoolType, IModuleWithState } from '../types'
import { uiItems } from '../uiItems'
import {
    setDomBoolVal,
    setDomDataItemVal,
    toBinaryStr,
    toInt255,
} from '../utils'
import { busInputToMultiplexer31RAI } from './bus'

interface IInputState {
    in_en: BoolType
    value: number
}

// 给页面中的输入框添加事件
function addInputEvent() {
    const dom = uiItems.input
    if (!dom) return
    dom.cursor = 'pointer'
    dom.on(PointerEvent.CLICK, async () => {
        const inputed = await ElMessageBox.prompt('输入：', {
            inputValue: toBinaryStr(input.state.value, 8, true),
        })
        // console.log(inputed)
        input.setState('value', toInt255(inputed.value))
        console.log('input clicked')
    })  
}

/**
 * input模块
 */
export const input: IModuleWithState<IInputState> = {
    name: 'input',
    state: {
        in_en: 0,
        value: 0,
    },
    async setState(prop, value) {
        this.state[prop] = value
        if (prop === 'in_en') {
            setDomBoolVal(prop, this.state[prop] as BoolType)
        } else if (prop === 'value') {
            setDomDataItemVal('.input.data-item', toBinaryStr(this.state[prop]))
        }
        if (prop !== 'value') {
            this.change!()
        }
        return
    },
    async change() {
        // 当in_en为1时，输入数据
        if (this.state.in_en === 1) {
            busInputToMultiplexer31RAI.setData(this.state.value)
            return
        }
    },
    init() {
        // 设置in_en的初始值
        setDomBoolVal('in_en', this.state.in_en)
        // 设置input
        setDomDataItemVal('.input.data-item', toBinaryStr(this.state['value']))
        // 给输入框添加事件
        addInputEvent()
    },
}
